"use strict";
$jq.namespace('PeopleMedia.CP');

PeopleMedia.CP.PhotoFeed = function () {
    this._siteId = PeopleMedia.CP.SiteID();
    this._members = [];
    this._photoContainerId = "divPhotoContainer";
    this._photoTemplateId = "divPhotoTemplate";
    this._imageType = "s";
    this._gender = null;
    this._minAge = null;
    this._maxAge = null;
    this._postalCode = null;
    this._postalCodeRadius = null;
    this._countryCode = null;
    this._photoOnly = null;
    this._optedInOnly = null;
    this._resultCount = null;
    this._profileUrl = null;
};

PeopleMedia.CP.PhotoFeed.prototype = {
    Oid: "PeopleMedia.CP.PhotoFeed",
    SiteId: function (siteId) {
        if (arguments.length > 0) {
            this._siteId = siteId;
        } else {
            return this._siteId;
        }
    },
    Members: function (members) {
        if (arguments.length > 0) {
            this._members = members;
        } else {
            return this._members;
        }
    },
    PhotoContainerId: function (photoContainerId) {
        if (arguments.length > 0) {
            this._photoContainerId = photoContainerId;
        } else {
            return this._photoContainerId;
        }
    },
    PhotoTemplateId: function (photoTemplateId) {
        if (arguments.length > 0) {
            this._photoTemplateId = photoTemplateId;
        } else {
            return this._photoTemplateId;
        }
    },
    ImageType: function (imageType) {
        if (arguments.length > 0) {
            this._imageType = imageType;
        } else {
            return this._imageType;
        }
    },
    Gender: function (gender) {
        if (arguments.length > 0) {
            this._gender = gender;
        } else {
            return this._gender;
        }
    },
    MinAge: function (minAge) {
        if (arguments.length > 0) {
            this._minAge = minAge;
        } else {
            return this._minAge;
        }
    },
    MaxAge: function (maxAge) {
        if (arguments.length > 0) {
            this._maxAge = maxAge;
        } else {
            return this._maxAge;
        }
    },
    PostalCode: function (postalCode) {
        if (arguments.length > 0) {
            this._postalCode = postalCode;
        } else {
            return this._postalCode;
        }
    },
    PostalCodeRadius: function (postalCodeRadius) {
        if (arguments.length > 0) {
            this._postalCodeRadius = postalCodeRadius;
        } else {
            return this._postalCodeRadius;
        }
    },
    CountryCode: function (countryCode) {
        if (arguments.length > 0) {
            this._countryCode = countryCode;
        } else {
            return this._countryCode;
        }
    },
    PhotoOnly: function (photoOnly) {
        if (arguments.length > 0) {
            this._photoOnly = photoOnly;
        } else {
            return this._photoOnly;
        }
    },
    OptedInOnly: function (optedInOnly) {
        if (arguments.length > 0) {
            this._optedInOnly = optedInOnly;
        } else {
            return this._optedInOnly;
        }
    },
    ResultCount: function (resultCount) {
        if (arguments.length > 0) {
            this._resultCount = resultCount;
        } else {
            return this._resultCount;
        }
    },
    ProfileUrl: function (profileUrl) {
        if (arguments.length > 0) {
            this._profileUrl = profileUrl;
        } else {
            return this._profileUrl;
        }
    },
    loadPhotoContainer: function () {
        try {
            var thisObj = this;
            PeopleMedia.CP.Messaging.reset();
            this.reset();
            this.retrievePhotos(
                function (data) {
                    for (var i = 0; i < data.length; ++i) {
                        var html = thisObj.getItemHTML(data[i]);
                        $jq('#' + thisObj.PhotoContainerId()).append(html);
                    }
                },
                function (errors) {
                    var firstError = PeopleMedia.CP.getFirstError(errors);
                    if (!firstError || !firstError.IsAjaxError) {
                        PeopleMedia.CP.Messaging.show(errors);
                    }
                });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"loadPhotoContainer" });
        }
    },

    getItemHTML: function (item) {
        try {
            var gender = item.Gender == 1 ? "Male" : "Female";
            //var birthDate = PeopleMedia.CP.Utilities.dateStringToDate(item.BirthDate);
            //var birthDateString = (birthDate && birthDate.getMonth && birthDate.getDate && birthDate.getYear) ? ((birthDate.getMonth() + 1) + "/" + birthDate.getDate() + "/" + birthDate.getYear()) : "";
            //var age = PeopleMedia.CP.Utilities.calculateAgeInYears(birthDate);
            //var ageString = (age != null && age > 0) ? age.toString() : "";
			var birthDateString = item.BirthDate;
			var ageString = item.BirthDate;
            var primaryImageUrl = (item.PrimaryImage != null && item.PrimaryImage.ImageUrl != null) ? item.PrimaryImage.ImageUrl : "http://pmi0.peoplemedia.com/" + PeopleMedia.CP.SiteID() + "/stock/noPhoto-" + item.Gender + this.ImageType() + ".gif";
            primaryImageUrl = primaryImageUrl.replace(".jpg", this.ImageType() + ".jpg");
            var profileUrl = this.ProfileUrl();
            if (profileUrl == null) {
                profileUrl = item.ProfileUrl;
            }
			
            profileUrl = profileUrl.replace(/@MEMBER_ID@/g, item.Identifier);
            var html = $jq("#" + this.PhotoTemplateId()).html();
            html = html.replace(/@MEMBER_ID@/g, item.Identifier);
            html = html.replace(/@ENCODED_MEMBER_ID@/g, item.EncodedIdentifier);
            html = html.replace(/@USERNAME@/g, item.NickName);
            html = html.replace(/@BIRTH_DATE@/g, birthDateString);
            html = html.replace(/@AGE@/g, ageString);
            html = html.replace(/@GENDER@/g, gender);
            html = html.replace(/@CITY@/g, item.Location != null && item.Location.City != null ? item.Location.City : "");
            html = html.replace(/@STATE_CODE@/g, item.Location != null && item.Location.State != null && item.Location.State.StateReference != null && item.Location.State.StateReference.StateCode != null ? item.Location.State.StateReference.StateCode : "");
            html = html.replace(/@COUNTRY_CODE@/g, item.Location != null && item.Location.Country != null && item.Location.Country.ShortCode != null ? item.Location.Country.ShortCode : "");
            html = html.replace(/@COUNTRY@/g, item.Location != null && item.Location.Country != null && item.Location.Country.Name != null ? $jq.trim(item.Location.Country.Name) : "");
            html = html.replace(/http:\/\/@PROFILE_URL@/g, profileUrl);
            html = html.replace(/http:\/\/@PHOTO_URL@/g, primaryImageUrl);
            return html;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getItemHTML" });
            return "";
        }
    },

    retrievePhotos: function (onSuccess, onFailure) {
        try {
            var gender = null;
            if (!this.isNullOrEmpty(this.Gender())) {
                if (this.Gender() == 1 || this.Gender().toString().toLowerCase() == 'm' || this.Gender().toString().toLowerCase() == 'male') {
                    gender = 1;
                } else if (this.Gender() == 2 || this.Gender().toString().toLowerCase() == 'f' || this.Gender().toString().toLowerCase() == 'female') {
                    gender = 2;
                } else {
                    onFailure([{ "Text": "Invalid Gender"}]);
                    return;
                }
            }

            if (!this.isNullOrEmpty(this.MinAge())) {
                if (!PeopleMedia.Types.Byte(this.MinAge()).isValid()) {
                    onFailure([{ "Text": "Invalid Min Age"}]);
                    return;
                }
            }

            if (!this.isNullOrEmpty(this.MaxAge())) {
                if (!PeopleMedia.Types.Byte(this.MaxAge()).isValid()) {
                    onFailure([{ "Text": "Invalid Max Age"}]);
                    return;
                }
            }

            if (!this.isNullOrEmpty(this.PostalCode()) || !this.isNullOrEmpty(this.PostalCodeRadius())) {
                if (this.isNullOrEmpty(this.PostalCode()) || this.isNullOrEmpty(this.PostalCodeRadius())) {
                    onFailure([{ "Text": "For postal code search, postal code and radius must be provided"}]);
                    return;
                }
                if (this.isNullOrEmpty(this.CountryCode())) {
                    if (this.PostalCode().length > 5) {
                        this.CountryCode("CA");
                    } else {
                        this.CountryCode("US");
                    }
                }
            }
            if (!this.isNullOrEmpty(this.PhotoOnly())) {
                if (this.PhotoOnly().toLowerCase() != "true" && this.PhotoOnly().toLowerCase() != "false") {
                    onFailure([{ "Text": "Invalid Photo Only value"}]);
                    return;
                }
            }

            if (!this.isNullOrEmpty(this.OptedInOnly())) {
                if (this.OptedInOnly().toLowerCase() != "true" && this.OptedInOnly().toLowerCase() != "false") {
                    onFailure([{ "Text": "Invalid Opted In value"}]);
                    return;
                }
            }

            if (!this.isNullOrEmpty(this.ResultCount())) {
                if (!PeopleMedia.Types.Byte(this.ResultCount()).isValid()) {
                    onFailure([{ "Text": "Invalid Result Count"}]);
                    return;
                }
            }

            var thisObj = this;
            PeopleMedia.CP.ui_busy();
            var useMaiLpsApi = PeopleMedia.CP.UseMaiLpsApi();
            if (useMaiLpsApi) {
                var url = PeopleMedia.CP.LpsApiUrl() + "/GetSamplePhotos";
				
                var parms = {};
                if (!this.isNullOrEmpty(gender)) {
                    parms.gender = gender;
                }
                if (!this.isNullOrEmpty(this.MinAge())) {
                    parms.minAge = this.MinAge();
                }
                if (!this.isNullOrEmpty(this.MaxAge())) {
                    parms.maxAge = this.MaxAge();
                }
                if (!this.isNullOrEmpty(this.PostalCode())) {
                    parms.postalCode = this.PostalCode();
                }
                if (!this.isNullOrEmpty(this.PostalCodeRadius())) {
                    parms.postalCodeRadius = this.PostalCodeRadius();
                }
                if (!this.isNullOrEmpty(this.CountryCode())) {
                    parms.countryCode = this.CountryCode();
                }
                if (!this.isNullOrEmpty(this.PhotoOnly())) {
                    parms.photoOnly = this.PhotoOnly();
                }
                if (!this.isNullOrEmpty(this.OptedInOnly())) {
                    parms.optedInOnly = this.OptedInOnly();
                }
                if (!this.isNullOrEmpty(this.ResultCount())) {
                    parms.resultCount = this.ResultCount();
                }

                var startTime = new Date().getTime();
                var timeoutValue = 10000;
                jQuery.ajax({
                    type: "POST",
                    url: url,
                    data: parms,
                    dataType: "json",
                    success: function (data) {
                        thisObj.retrievePhotos_complete(onSuccess, onFailure, data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime = new Date().getTime();
                        var duration = (endTime - startTime);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                            PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "retrievePhotos", duration: duration, useMaiLpsApi: useMaiLpsApi }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                        thisObj.retrievePhotos_complete(onSuccess, onFailure, data);
                    },
                    async: true,
                    cache: false,
                    timeout: timeoutValue
                });
            } else {
                var url = PeopleMedia.CP.getPMApiBaseUrl("GetSamplePhotos");
				var url1 = url + '/GetSamplePhotos';
				var form_data = {};
				
				form_data.seeking = $jq.queryString.get("seeking");
                url += "&communityNameOrID=" + PeopleMedia.CP.SiteID();
				form_data.communityNameOrID = PeopleMedia.CP.SiteID();
                if (!this.isNullOrEmpty(gender)) {
                    url += "&gender=" + gender;
					form_data.gender = gender;
                }
                if (!this.isNullOrEmpty(this.MinAge())) {
                    url += "&minAge=" + this.MinAge();
					form_data.minAge = this.MinAge();
                }
                if (!this.isNullOrEmpty(this.MaxAge())) {
                    url += "&maxAge=" + this.MaxAge();
					form_data.maxAge = this.MaxAge();
                }
                if (!this.isNullOrEmpty(this.PostalCode())) {
                    url += "&postalCode=" + this.PostalCode();
					form_data.postalCode = this.PostalCode();
                }
                if (!this.isNullOrEmpty(this.PostalCodeRadius())) {
                    url += "&postalCodeRadius=" + this.PostalCodeRadius();
					form_data.postalCodeRadius = this.PostalCodeRadius();
                }
                if (!this.isNullOrEmpty(this.CountryCode())) {
                    url += "&countryCode=" + this.CountryCode();
					form_data.countryCode = this.CountryCode();
                }
                if (!this.isNullOrEmpty(this.PhotoOnly())) {
                    url += "&photoOnly=" + this.PhotoOnly();
					form_data.photoOnly = this.PhotoOnly();
                }
                if (!this.isNullOrEmpty(this.OptedInOnly())) {
                    url += "&optedInOnly=" + this.OptedInOnly();
					form_data.optedInOnly = this.OptedInOnly();
                }
                if (!this.isNullOrEmpty(this.ResultCount())) {
                    url += "&resultCount=" + this.ResultCount();
					form_data.resultCount = this.ResultCount();
                }
                url += "&callbackMethod=?";
				form_data.callbackMethod = '?';

                var startTime2 = new Date().getTime();
                var timeoutValue2 = 10000;
				//alert(url);
                jQuery.ajax({
                    type: "POST",
                    url: url1,
                    dataType: "json",
					data: form_data,
                    success: function (data) {
                        thisObj.retrievePhotos_complete(onSuccess, onFailure, data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime2 = new Date().getTime();
                        var duration2 = (endTime2 - startTime2);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                            PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "retrievePhotos", duration: duration2, useMaiLpsApi: useMaiLpsApi }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                        thisObj.retrievePhotos_complete(onSuccess, onFailure, data);
                    },
                    async: true,
                    cache: false,
                    timeout: timeoutValue2
                });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"retrievePhotos" });
        }
    },
    retrievePhotos_complete: function (onSuccess, onFailure, data) {
        try {
            var errors = [];
            PeopleMedia.CP.ui_done();
            if (data.Fault) {
                if (!data.Fault.IsCancelled) {
                    errors.push(PeopleMedia.CP.convertFaultToError(data.Fault));
                }
                onFailure(errors);
            } else {
                this.Members(data);
                onSuccess(data);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"retrievePhotos_complete" });
        }
    },
    reset: function () {
        try {
            this.Members([]);
            if (this.PhotoContainerId != null) {
                $jq('#' + this.PhotoContainerId()).html("");
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"reset" });
        }
    },
    isNullOrEmpty: function (obj) {
        try {
            if (obj == undefined || obj == null) {
                return true;
            } else if (typeof (obj) == "string") {
                return $jq.trim(obj).length <= 0;
            } else {
                return false;
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isNullOrEmpty" });
            return true;
        }
    }
};
